<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>获取地理位置</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        max-width: 600px;
        margin: 2rem auto;
        padding: 0 1rem;
      }
      button {
        padding: 0.8rem 1.5rem;
        background: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: background 0.3s;
      }
      button:hover {
        background: #0056b3;
      }
      #result {
        margin-top: 1rem;
        padding: 1rem;
        border: 1px solid #ddd;
        border-radius: 4px;
      }
      .error {
        color: #dc3545;
      }
    </style>
  </head>
  <body>
    <h1>获取地理位置</h1>
    <button onclick="beforeMount()">获取我的位置</button>
    <div id="result"></div>

    <script>
      function beforeMount() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            this.getLocationSuccess,
            this.getLocationError
          );
        } else {
          console.log("浏览器不支持Geolocation API");
        }
      }

      /**
       * @description: 成功回调函数
       * @param {object} position 地理位置
       */
      function getLocationSuccess(position) {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
        document.getElementById("result").innerHTML =
          "当前位置经度：" + longitude + "<br>" + "当前位置纬度：" + latitude;
        console.log("当前位置经度：" + longitude);
        console.log("当前位置纬度：" + latitude);
      }

      /**
       * @description: 失败回调函数
       * @param {object} error 错误信息
       */
      function getLocationError(error) {
        switch (error.code) {
          case error.PERMISSION_DENIED:
            console.log("用户拒绝了位置请求");
            break;
          case error.POSITION_UNAVAILABLE:
            console.log("无法获取当前位置");
            break;
          case error.TIMEOUT:
            console.log("获取位置超时");
            break;
          case error.UNKNOWN_ERROR:
            console.log("发生未知错误");
            break;
        }
      }
    </script>
  </body>
</html>
